﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ZeroSum.DependencyInjection.Attributes;
using ZeroSum.Domain.Repositories;
using ZeroSum.Extend.EFCore.MySql.Extensions;
using ZeroSum.Plugin.Authorization.Datas.Services.Roles;
using ZeroSumZSA.Core.Aggregates.RoleAggregate;

namespace ZeroSumZSA.Core.DomainServices.Roles;

[Register(ServiceLifetime.Transient)]
public class RoleDomainService : RoleBaseDomainService<Role>, IRoleDomainService
{
    public RoleDomainService(IRepository<Role, long> roleRepository) : base(roleRepository)
    {
    }

    public Task<IList<Role>> Query(string? keyword, int page, int size)
    {
        var query = GetQueryBy(keyword).Paged(page, size);
        return RoleRepository.GetListAsync(query);
    }

    public Task<int> Count(string? keyword)
    {
        var query = GetQueryBy(keyword);
        return RoleRepository.CountAsync(query);
    }

    private QueryByEntity<Role> GetQueryBy(string? keyword)
    {
        var notEmpty = !string.IsNullOrEmpty(keyword?.Trim());

        IQueryable<Role> Func(IQueryable<Role> query)
        {
            return query.WhereIf(notEmpty,
                    u => EF.Functions.Like(u.Name!, $"%{keyword!.Trim()}%") ||
                         EF.Functions.Like(u.Code!, $"%{keyword.Trim()}%"))
                .OrderBy(x => x.Sort);
        }

        return QueryByEntity<Role>.Of(Func);
    }
}